import React, { useState, useEffect, useRef } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { Input } from './ui/input';
import { Brain, Clock, Trophy, Star, Target, ArrowRight, RotateCcw, CheckCircle, XCircle } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';

interface WorkingMemoryTestProps {
  onComplete: (result: TestResult) => void;
}

interface Task {
  id: number;
  type: 'digit_span' | 'spatial_sequence' | 'visual_matrix' | 'nback';
  instruction: string;
  spanLength: number;
  reverse?: boolean;
  difficulty: 'easy' | 'medium' | 'hard';
}

interface Response {
  sequence: any[];
  accuracy: number;
  reactionTime: number;
  spanLength: number;
  taskType: string;
}

export function WorkingMemoryTest({ onComplete }: WorkingMemoryTestProps) {
  const [stage, setStage] = useState<'instructions' | 'test' | 'presenting' | 'recall' | 'feedback' | 'results'>('instructions');
  const [currentTask, setCurrentTask] = useState(0);
  const [tasks, setTasks] = useState<Task[]>([]);
  const [currentSequence, setCurrentSequence] = useState<any[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);  
  const [userInput, setUserInput] = useState('');
  const [selectedCells, setSelectedCells] = useState<{ x: number; y: number }[]>([]);
  const [responses, setResponses] = useState<Response[]>([]);
  const [startTime, setStartTime] = useState<number>(0);
  const [taskStartTime, setTaskStartTime] = useState<number>(0);
  const [score, setScore] = useState(0);
  const [showFeedback, setShowFeedback] = useState(false);
  const [feedbackCorrect, setFeedbackCorrect] = useState(false);
  const [feedbackDetails, setFeedbackDetails] = useState<{
    correctAnswer: any[];
    userAnswer: any[];
    accuracy: number;
    taskType: string;
    errors: string[];
  } | null>(null);
  const [matrixCells, setMatrixCells] = useState<{x: number, y: number, highlighted: boolean}[]>([]);
  const [matrixSize] = useState(4);
  const [presentingItem, setPresentingItem] = useState<any>(null);

  const TOTAL_TASKS = 12;
  const DIGITS = [1, 2, 3, 4, 5, 6, 7, 8, 9];

  // 生成测试任务
  const generateTasks = (): Task[] => {
    const tasks: Task[] = [];
    let taskId = 1;

    // 数字广度测试 (正序和逆序)
    for (let length = 3; length <= 7; length++) {
      tasks.push({
        id: taskId++,
        type: 'digit_span',
        instruction: `记住这个${length}位数字序列，然后按顺序输入`,
        spanLength: length,
        reverse: false,
        difficulty: length <= 4 ? 'easy' : length <= 6 ? 'medium' : 'hard'
      });
      
      if (length >= 4) {
        tasks.push({
          id: taskId++,
          type: 'digit_span',
          instruction: `记住这个${length}位数字序列，然后按倒序输入`,
          spanLength: length,
          reverse: true,
          difficulty: length <= 4 ? 'easy' : length <= 6 ? 'medium' : 'hard'
        });
      }
    }

    // 空间序列测试
    for (let length = 3; length <= 6; length++) {
      tasks.push({
        id: taskId++,
        type: 'spatial_sequence',
        instruction: `记住方格高亮的顺序，然后按相同顺序点击`,
        spanLength: length,
        difficulty: length <= 4 ? 'easy' : length <= 5 ? 'medium' : 'hard'
      });
    }

    // 视觉矩阵测试
    for (let count = 3; count <= 8; count += 2) {
      tasks.push({
        id: taskId++,
        type: 'visual_matrix',
        instruction: `记住高亮方格的位置，然后点击这些位置`,
        spanLength: count,
        difficulty: count <= 4 ? 'easy' : count <= 6 ? 'medium' : 'hard'
      });
    }

    // 随机选择并排序任务
    return tasks.sort(() => Math.random() - 0.5).slice(0, TOTAL_TASKS);
  };

  // 生成数字序列
  const generateDigitSequence = (length: number) => {
    const sequence = [];
    for (let i = 0; i < length; i++) {
      sequence.push(DIGITS[Math.floor(Math.random() * DIGITS.length)]);
    }
    return sequence;
  };

  // 生成空间序列
  const generateSpatialSequence = (length: number) => {
    const sequence = [];
    const used = new Set<string>();
    
    for (let i = 0; i < length; i++) {
      let x, y, key;
      do {
        x = Math.floor(Math.random() * 3);
        y = Math.floor(Math.random() * 3);
        key = `${x},${y}`;
      } while (used.has(key));
      
      used.add(key);
      sequence.push({ x, y });
    }
    
    return sequence;
  };

  // 生成视觉矩阵
  const generateVisualMatrix = (count: number) => {
    const cells = [];
    const highlighted = [];
    
    // 创建所有格子
    for (let x = 0; x < matrixSize; x++) {
      for (let y = 0; y < matrixSize; y++) {
        cells.push({ x, y, highlighted: false });
      }
    }
    
    // 随机选择要高亮的格子
    const shuffled = [...cells].sort(() => Math.random() - 0.5);
    for (let i = 0; i < count; i++) {
      shuffled[i].highlighted = true;
      highlighted.push({ x: shuffled[i].x, y: shuffled[i].y });
    }
    
    setMatrixCells(cells);
    return highlighted;
  };

  // 开始展示序列
  const startPresenting = async () => {
    const task = tasks[currentTask];
    
    // 准备阶段 - 倒计时3秒
    setStage('presenting');
    
    // 倒计时
    for (let countdown = 3; countdown > 0; countdown--) {
      setPresentingItem(`准备... ${countdown}`);
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
    
    setPresentingItem('开始！');
    await new Promise(resolve => setTimeout(resolve, 500));
    
    setCurrentIndex(0);
    
    if (task.type === 'digit_span') {
      const sequence = generateDigitSequence(task.spanLength);
      setCurrentSequence(sequence);
      
      // 逐个展示数字
      for (let i = 0; i < sequence.length; i++) {
        setPresentingItem(sequence[i]);
        setCurrentIndex(i);
        await new Promise(resolve => setTimeout(resolve, 1200));
      }
      
    } else if (task.type === 'spatial_sequence') {
      const sequence = generateSpatialSequence(task.spanLength);
      setCurrentSequence(sequence);
      
      setPresentingItem('观看方格高亮');
      await new Promise(resolve => setTimeout(resolve, 800));
      
      // 逐个高亮空间位置
      for (let i = 0; i < sequence.length; i++) {
        setPresentingItem(sequence[i]);
        setCurrentIndex(i);
        await new Promise(resolve => setTimeout(resolve, 1000));
        setPresentingItem(null);
        await new Promise(resolve => setTimeout(resolve, 300));
      }
      
    } else if (task.type === 'visual_matrix') {
      const highlighted = generateVisualMatrix(task.spanLength);
      setCurrentSequence(highlighted);
      
      setPresentingItem('观看高亮位置');
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 显示矩阵2.5秒
      await new Promise(resolve => setTimeout(resolve, 2500));
      setMatrixCells(prev => prev.map(cell => ({ ...cell, highlighted: false })));
    }
    
    setPresentingItem(null);
    setStage('recall');
  };

  // 分析错误详情
  const analyzeErrors = (userSeq: any[], correctSeq: any[], taskType: string): string[] => {
    const errors: string[] = [];
    
    if (taskType === 'digit_span') {
      const task = tasks[currentTask];
      if (userSeq.length !== correctSeq.length) {
        errors.push(`长度错误：应该输入${correctSeq.length}位数字，您输入了${userSeq.length}位`);
      }
      
      const minLength = Math.min(userSeq.length, correctSeq.length);
      for (let i = 0; i < minLength; i++) {
        if (userSeq[i] !== correctSeq[i]) {
          errors.push(`第${i + 1}位错误：应该是${correctSeq[i]}，您输入的是${userSeq[i]}`);
        }
      }
      
      if (userSeq.length > correctSeq.length) {
        errors.push(`多输入了${userSeq.length - correctSeq.length}位数字`);
      } else if (userSeq.length < correctSeq.length) {
        errors.push(`少输入了${correctSeq.length - userSeq.length}位数字`);
      }
      
    } else if (taskType === 'spatial_sequence') {
      if (userSeq.length !== correctSeq.length) {
        errors.push(`点击次数错误：应该点击${correctSeq.length}个方格，您点击了${userSeq.length}个`);
      }
      
      const minLength = Math.min(userSeq.length, correctSeq.length);
      for (let i = 0; i < minLength; i++) {
        const userPos = userSeq[i];
        const correctPos = correctSeq[i];
        if (!userPos || !correctPos || userPos.x !== correctPos.x || userPos.y !== correctPos.y) {
          const userPosStr = userPos ? `(${userPos.x + 1}, ${userPos.y + 1})` : '未选择';
          const correctPosStr = `(${correctPos.x + 1}, ${correctPos.y + 1})`;
          errors.push(`第${i + 1}步错误：应该点击位置${correctPosStr}，您点击的是${userPosStr}`);
        }
      }
      
    } else if (taskType === 'visual_matrix') {
      const correctPositions = correctSeq.map(pos => `${pos.x},${pos.y}`);
      const selectedPositions = userSeq.map(pos => `${pos.x},${pos.y}`);
      
      const missed = correctPositions.filter(pos => !selectedPositions.includes(pos));
      const wrongSelected = selectedPositions.filter(pos => !correctPositions.includes(pos));
      
      if (missed.length > 0) {
        const missedCoords = missed.map(pos => {
          const [x, y] = pos.split(',').map(Number);
          return `(${x + 1}, ${y + 1})`;
        });
        errors.push(`遗漏位置：${missedCoords.join(', ')}`);
      }
      
      if (wrongSelected.length > 0) {
        const wrongCoords = wrongSelected.map(pos => {
          const [x, y] = pos.split(',').map(Number);
          return `(${x + 1}, ${y + 1})`;
        });
        errors.push(`错误选择：${wrongCoords.join(', ')}`);
      }
    }
    
    return errors;
  };

  // 处理用户回答
  const handleAnswer = () => {
    const task = tasks[currentTask];
    const reactionTime = Date.now() - taskStartTime;
    let accuracy = 0;
    let userSequence: any[] = [];
    let correctSequence: any[] = [];
    
    if (task.type === 'digit_span') {
      userSequence = userInput.split('').map(d => parseInt(d)).filter(n => !isNaN(n));
      correctSequence = task.reverse ? [...currentSequence].reverse() : [...currentSequence];
      accuracy = calculateSequenceAccuracy(userSequence, correctSequence);
      
    } else if (task.type === 'spatial_sequence') {
      userSequence = selectedCells || [];
      correctSequence = currentSequence || [];
      accuracy = calculateSpatialAccuracy(userSequence, correctSequence);
      
    } else if (task.type === 'visual_matrix') {
      userSequence = selectedCells || [];
      correctSequence = currentSequence || [];
      accuracy = calculateMatrixAccuracy(userSequence, correctSequence);
    }
    
    const response: Response = {
      sequence: userSequence,
      accuracy,
      reactionTime,
      spanLength: task.spanLength,
      taskType: task.type
    };
    
    setResponses(prev => [...prev, response]);
    
    const isCorrect = accuracy >= 0.8;
    if (isCorrect) {
      setScore(prev => prev + 1);
    }
    
    // 分析错误
    const errors = isCorrect ? [] : analyzeErrors(userSequence, correctSequence, task.type);
    
    // 显示反馈
    setFeedbackCorrect(isCorrect);
    setFeedbackDetails({
      correctAnswer: correctSequence,
      userAnswer: userSequence,
      accuracy: Math.round(accuracy * 100),
      taskType: task.type,
      errors
    });
    setShowFeedback(true);
    setStage('feedback');
    
    // 移除自动跳转，改为手动控制
  };

  // 继续下一题
  const handleContinue = () => {
    setShowFeedback(false);
    setFeedbackDetails(null);
    setUserInput('');
    setSelectedCells([]);
    
    if (currentTask < tasks.length - 1) {
      setCurrentTask(prev => prev + 1);
      setStage('test');
    } else {
      setStage('results');
    }
  };

  // 计算序列准确率
  const calculateSequenceAccuracy = (userSeq: number[], correctSeq: number[]): number => {
    if (userSeq.length === 0) return 0;
    
    const minLength = Math.min(userSeq.length, correctSeq.length);
    let correct = 0;
    
    for (let i = 0; i < minLength; i++) {
      if (userSeq[i] === correctSeq[i]) {
        correct++;
      }
    }
    
    return correct / correctSeq.length;
  };

  // 计算空间序列准确率
  const calculateSpatialAccuracy = (userSeq: {x: number, y: number}[], correctSeq: {x: number, y: number}[]): number => {
    if (!userSeq || userSeq.length === 0 || !correctSeq || correctSeq.length === 0) return 0;
    
    const minLength = Math.min(userSeq.length, correctSeq.length);
    let correct = 0;
    
    for (let i = 0; i < minLength; i++) {
      const userItem = userSeq[i];
      const correctItem = correctSeq[i];
      if (userItem && 
          correctItem && 
          typeof userItem.x === 'number' && 
          typeof userItem.y === 'number' &&
          typeof correctItem.x === 'number' && 
          typeof correctItem.y === 'number' &&
          userItem.x === correctItem.x && 
          userItem.y === correctItem.y) {
        correct++;
      }
    }
    
    return correct / correctSeq.length;
  };

  // 计算矩阵准确率
  const calculateMatrixAccuracy = (selected: {x: number, y: number}[], correct: {x: number, y: number}[]): number => {
    if (!selected || !correct || selected.length === 0 || correct.length === 0) return 0;
    
    const correctPositions = correct
      .filter(pos => pos && typeof pos.x === 'number' && typeof pos.y === 'number')
      .map(pos => `${pos.x},${pos.y}`);
    const selectedPositions = selected
      .filter(pos => pos && typeof pos.x === 'number' && typeof pos.y === 'number')
      .map(pos => `${pos.x},${pos.y}`);
    
    const truePositives = selectedPositions.filter(pos => correctPositions.includes(pos)).length;
    const falsePositives = selectedPositions.filter(pos => !correctPositions.includes(pos)).length;
    const falseNegatives = correctPositions.filter(pos => !selectedPositions.includes(pos)).length;
    
    if (truePositives + falsePositives + falseNegatives === 0) return 1;
    
    return truePositives / (truePositives + falsePositives + falseNegatives);
  };

  // 处理空间序列点击
  const handleSpatialClick = (x: number, y: number) => {
    if (typeof x === 'number' && typeof y === 'number') {
      setSelectedCells(prev => [...prev, { x, y }]);
    }
  };

  // 处理矩阵格子点击
  const handleMatrixCellClick = (x: number, y: number) => {
    if (typeof x !== 'number' || typeof y !== 'number') return;
    
    setSelectedCells(prev => {
      if (!prev) return [{ x, y }];
      
      const existing = prev.find(cell => cell && cell.x === x && cell.y === y);
      if (existing) {
        return prev.filter(cell => cell && !(cell.x === x && cell.y === y));
      } else {
        return [...prev, { x, y }];
      }
    });
  };

  // 开始测试
  const handleStartTest = () => {
    const generatedTasks = generateTasks();
    setTasks(generatedTasks);
    setStage('test');
    setStartTime(Date.now());
  };

  // 完成测试
  const handleComplete = () => {
    const totalTasks = tasks.length;
    const correctAnswers = score;
    const accuracy = Math.round((correctAnswers / totalTasks) * 100);
    const timeUsed = Math.round((Date.now() - startTime) / 1000);
    const averageSpan = responses.reduce((sum, r) => sum + r.spanLength, 0) / responses.length;
    const averageReactionTime = responses.reduce((sum, r) => sum + r.reactionTime, 0) / responses.length;

    // 按任务类型统计
    const typeStats: { [key: string]: { accuracy: number; count: number; avgSpan: number } } = {};
    
    responses.forEach(response => {
      const type = response.taskType;
      if (!typeStats[type]) {
        typeStats[type] = { accuracy: 0, count: 0, avgSpan: 0 };
      }
      typeStats[type].accuracy += response.accuracy;
      typeStats[type].avgSpan += response.spanLength;
      typeStats[type].count++;
    });

    // 计算平均值
    Object.keys(typeStats).forEach(type => {
      const stats = typeStats[type];
      stats.accuracy = Math.round((stats.accuracy / stats.count) * 100);
      stats.avgSpan = Math.round((stats.avgSpan / stats.count) * 10) / 10;
    });

    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'working-memory',
      score: accuracy,
      completedAt: new Date(),
      duration: timeUsed,
      details: {
        totalTasks,
        correctAnswers,
        accuracy,
        averageSpanLength: Math.round(averageSpan * 10) / 10,
        maxSpanLength: Math.max(...responses.map(r => r.spanLength)),
        averageReactionTime: Math.round(averageReactionTime),
        typeBreakdown: Object.entries(typeStats).map(([type, stats]) => ({
          type: type === 'digit_span' ? '数字广度' :
                type === 'spatial_sequence' ? '空间序列' :
                type === 'visual_matrix' ? '视觉矩阵' : type,
          accuracy: stats.accuracy,
          avgSpan: stats.avgSpan,
          count: stats.count
        })),
        totalQuestions: totalTasks,
        correctQuestions: correctAnswers,
        averageTime: timeUsed,
        difficulty: 'adaptive'
      }
    };

    onComplete(result);
  };

  // 开始当前任务
  useEffect(() => {
    if (stage === 'test' && tasks.length > 0) {
      setTaskStartTime(Date.now());
      // 移除自动开始，改为用户手动控制
    }
  }, [currentTask, stage]);

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-indigo-600 to-blue-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Brain className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">工作记忆测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您的工作记忆容量和处理能力</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-indigo-50 to-blue-50 rounded-xl p-6 border border-indigo-100">
              <h3 className="font-semibold text-indigo-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-indigo-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>观察并记住呈现的序列或模式</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-indigo-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>包括数字序列、空间位置、视觉矩阵等任务</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-indigo-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>序列长度会根据表现动态调整</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-indigo-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>准确性比速度更重要，仔细回忆</p>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-4 border border-blue-200">
                <h4 className="font-semibold text-blue-800 mb-2 flex items-center gap-2">
                  <Target className="w-4 h-4" />
                  数字序列
                </h4>
                <p className="text-sm text-blue-700">记忆数字的顺序和逆序</p>
              </div>
              <div className="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-4 border border-purple-200">
                <h4 className="font-semibold text-purple-800 mb-2 flex items-center gap-2">
                  <ArrowRight className="w-4 h-4" />
                  空间记忆
                </h4>
                <p className="text-sm text-purple-700">记住位置的空间序列</p>
              </div>
              <div className="bg-gradient-to-br from-green-50 to-green-100 rounded-xl p-4 border border-green-200">
                <h4 className="font-semibold text-green-800 mb-2 flex items-center gap-2">
                  <Star className="w-4 h-4" />
                  视觉矩阵
                </h4>
                <p className="text-sm text-green-700">记住方格的空间模式</p>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-xl border border-indigo-200">
                <div className="text-2xl font-bold text-indigo-600 mb-1">3</div>
                <div className="text-sm text-indigo-700">任务类型</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl border border-blue-200">
                <div className="text-2xl font-bold text-blue-600 mb-1">12</div>
                <div className="text-sm text-blue-700">测试轮次</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-indigo-50 to-blue-50 rounded-xl border border-indigo-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">自适应</div>
                <div className="text-sm text-slate-700">难度调节</div>
              </div>
            </div>

            <Button 
              onClick={handleStartTest}
              className="w-full bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0 min-w-[140px] h-12"
              size="lg"
            >
              开始测试
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test' && tasks.length > 0) {
    const task = tasks[currentTask];
    const progress = (currentTask / tasks.length) * 100;

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 进度条和状态 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-indigo-100 text-indigo-700 border-indigo-300">
              任务 {currentTask + 1} / {tasks.length}
            </Badge>
            <Badge variant="outline" className="bg-blue-100 text-blue-700 border-blue-300">
              长度: {task.spanLength}
            </Badge>
            <div className="flex items-center gap-2 text-slate-600">
              <Trophy className="w-4 h-4" />
              <span className="font-semibold">{score}</span>
            </div>
          </div>
        </div>

        <Progress value={progress} className="h-2" />

        {/* 任务说明和开始按钮 */}
        <Card className="bg-gradient-to-r from-slate-50 to-gray-50 border-slate-200">
          <CardHeader>
            <CardTitle className="text-lg text-slate-800 text-center mb-4">
              {task.instruction}
            </CardTitle>
            <div className="space-y-4 text-center">
              <p className="text-slate-600">请仔细阅读上述说明</p>
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 space-y-2">
                <h4 className="font-semibold text-blue-800">测试流程：</h4>
                <div className="text-sm text-blue-700 space-y-1">
                  <p>1. 点击"准备开始"后将开始展示序列</p>
                  <p>2. 请专注观看并记住内容</p>
                  <p>3. 展示结束后请准确回忆</p>
                </div>
              </div>
              <Button
                onClick={startPresenting}
                className="bg-gradient-to-r from-indigo-600 to-blue-500 hover:from-indigo-700 hover:to-blue-600 text-white px-8 py-2 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
                size="lg"
              >
                <Brain className="w-5 h-5 mr-2" />
                准备开始
              </Button>
            </div>
          </CardHeader>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'presenting' && tasks.length > 0) {
    const task = tasks[currentTask];

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-lg">
          <CardContent className="p-8">
            <div className="text-center">
              {task.type === 'digit_span' && (
                <div className="space-y-4">
                  <div className="text-sm text-slate-500 mb-2">数字序列 - 请记住顺序</div>
                  <div className="text-8xl font-mono font-bold text-indigo-600">
                    {presentingItem || ''}
                  </div>
                  {typeof presentingItem === 'number' && (
                    <div className="text-lg text-slate-600">
                      {currentIndex + 1} / {currentSequence.length}
                    </div>
                  )}
                  {typeof presentingItem === 'string' && presentingItem.includes('准备') && (
                    <div className="text-base text-slate-500">
                      请集中注意力
                    </div>
                  )}
                </div>
              )}
              
              {task.type === 'spatial_sequence' && (
                <div className="space-y-4">
                  <div className="text-sm text-slate-500 mb-2">空间序列 - 请记住高亮顺序</div>
                  
                  {/* 显示倒计时或提示文本 */}
                  {typeof presentingItem === 'string' && (
                    <div className="text-2xl font-bold text-indigo-600 mb-4">
                      {presentingItem}
                    </div>
                  )}
                  
                  <div className="grid grid-cols-3 gap-4 max-w-xs mx-auto">
                    {Array.from({ length: 9 }, (_, i) => {
                      const x = i % 3;
                      const y = Math.floor(i / 3);
                      const isHighlighted = presentingItem && 
                                          typeof presentingItem === 'object' && 
                                          presentingItem !== null &&
                                          'x' in presentingItem && 
                                          'y' in presentingItem &&
                                          presentingItem.x === x && 
                                          presentingItem.y === y;
                      
                      return (
                        <div
                          key={i}
                          className={`w-20 h-20 rounded-lg border-2 transition-all duration-300 relative ${
                            isHighlighted 
                              ? 'bg-indigo-500 border-indigo-600 shadow-lg scale-110' 
                              : 'bg-slate-100 border-slate-300'
                          }`}
                        >
                          <div className={`absolute top-1 left-1 text-xs font-mono ${
                            isHighlighted ? 'text-white' : 'text-slate-400'
                          }`}>
                            {x + 1},{y + 1}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                  
                  {presentingItem && 
                   typeof presentingItem === 'object' && 
                   presentingItem !== null &&
                   'x' in presentingItem && 
                   typeof presentingItem.x === 'number' && (
                    <div className="text-lg text-slate-600">
                      {currentIndex + 1} / {currentSequence.length}
                    </div>
                  )}
                </div>
              )}
              
              {task.type === 'visual_matrix' && (
                <div className="space-y-4">
                  <div className="text-sm text-slate-500 mb-2">视觉矩阵 - 请记住高亮位置</div>
                  
                  {/* 显示倒计时或提示文本 */}
                  {typeof presentingItem === 'string' && (
                    <div className="text-2xl font-bold text-indigo-600 mb-4">
                      {presentingItem}
                    </div>
                  )}
                  
                  <div className={`grid gap-2 max-w-md mx-auto`} style={{ gridTemplateColumns: `repeat(${matrixSize}, 1fr)` }}>
                    {matrixCells.map((cell, index) => (
                      <div
                        key={index}
                        className={`w-16 h-16 rounded border-2 transition-all duration-300 ${
                          cell.highlighted 
                            ? 'bg-indigo-500 border-indigo-600 shadow-lg' 
                            : 'bg-slate-100 border-slate-300'
                        }`}
                      />
                    ))}
                  </div>
                  
                  {!presentingItem && (
                    <>
                      <div className="text-lg text-slate-600">
                        请记住所有高亮方格的位置
                      </div>
                      <div className="text-sm text-slate-500">
                        展示时间：2.5秒
                      </div>
                    </>
                  )}
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'recall' && tasks.length > 0) {
    const task = tasks[currentTask];

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-lg">
          <CardHeader>
            <CardTitle className="text-lg text-slate-800 text-center">
              请回忆刚才看到的内容
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            {task.type === 'digit_span' && (
              <div className="space-y-4">
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <h4 className="font-semibold text-blue-800 mb-2">输入说明：</h4>
                  <p className="text-sm text-blue-700">
                    {task.reverse 
                      ? '请将刚才看到的数字按倒序（从后往前）输入' 
                      : '请将刚才看到的数字按正序（从前往后）输入'}
                  </p>
                  <p className="text-xs text-blue-600 mt-1">
                    例如：看到 1-2-3 → {task.reverse ? '倒序输入 321' : '正序输入 123'}
                  </p>
                </div>
                <Input
                  value={userInput}
                  onChange={(e) => setUserInput(e.target.value)}
                  placeholder={task.reverse ? "倒序输入：如321" : "正序输入：如123"}
                  className="working-memory-input text-xl text-center py-3"
                  maxLength={task.spanLength}
                />
                <p className="text-sm text-slate-500 text-center">
                  长度：{task.spanLength}位数字
                </p>
              </div>
            )}
            
            {task.type === 'spatial_sequence' && (
              <div className="space-y-4">
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <h4 className="font-semibold text-blue-800 mb-2">点击说明：</h4>
                  <p className="text-sm text-blue-700">
                    请按照刚才看到的方格高亮顺序，依次点击对应的方格
                  </p>
                  <p className="text-xs text-blue-600 mt-1">
                    方格上的数字表示您的点击顺序
                  </p>
                </div>
                <div className="grid grid-cols-3 gap-4 max-w-xs mx-auto">
                  {Array.from({ length: 9 }, (_, i) => {
                    const x = i % 3;
                    const y = Math.floor(i / 3);
                    const orderIndex = selectedCells ? selectedCells.findIndex(cell => cell && cell.x === x && cell.y === y) : -1;
                    const isSelected = orderIndex >= 0;
                    
                    return (
                      <Button
                        key={i}
                        variant="outline"
                        onClick={() => handleSpatialClick(x, y)}
                        disabled={isSelected}
                        className={`w-20 h-20 p-0 text-xl font-bold transition-all duration-200 relative ${
                          isSelected 
                            ? 'bg-indigo-500 border-indigo-600 text-white scale-95' 
                            : 'hover:bg-indigo-50 hover:border-indigo-300'
                        }`}
                      >
                        <div className={`absolute top-1 left-1 text-xs font-mono ${
                          isSelected ? 'text-indigo-200' : 'text-slate-400'
                        }`}>
                          {x + 1},{y + 1}
                        </div>
                        {isSelected && (
                          <span className="text-xl font-bold">{orderIndex + 1}</span>
                        )}
                      </Button>
                    );
                  })}
                </div>
                <p className="text-center">
                  <span className="text-lg font-semibold text-indigo-600">
                    进度：{selectedCells ? selectedCells.length : 0}/{task.spanLength}
                  </span>
                </p>
              </div>
            )}
            
            {task.type === 'visual_matrix' && (
              <div className="space-y-4">
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <h4 className="font-semibold text-blue-800 mb-2">选择说明：</h4>
                  <p className="text-sm text-blue-700">
                    请点击刚才高亮的所��方格位置（顺序不限）
                  </p>
                  <p className="text-xs text-blue-600 mt-1">
                    可以重复点击来取消选择
                  </p>
                </div>
                <div className={`grid gap-2 max-w-md mx-auto`} style={{ gridTemplateColumns: `repeat(${matrixSize}, 1fr)` }}>
                  {matrixCells && matrixCells.map((cell, index) => {
                    if (!cell || typeof cell.x !== 'number' || typeof cell.y !== 'number') return null;
                    
                    const isSelected = selectedCells ? selectedCells.some(selected => selected && selected.x === cell.x && selected.y === cell.y) : false;
                    
                    return (
                      <Button
                        key={index}
                        variant="outline"
                        onClick={() => handleMatrixCellClick(cell.x, cell.y)}
                        className={`w-16 h-16 p-0 transition-all duration-200 relative ${
                          isSelected 
                            ? 'bg-indigo-500 border-indigo-600 scale-95' 
                            : 'hover:bg-indigo-50 hover:border-indigo-300'
                        }`}
                      >
                        <div className={`absolute top-0.5 left-0.5 text-xs font-mono ${
                          isSelected ? 'text-indigo-200' : 'text-slate-400'
                        }`}>
                          {cell.x + 1},{cell.y + 1}
                        </div>
                      </Button>
                    );
                  })}
                </div>
                <p className="text-center">
                  <span className="text-lg font-semibold text-indigo-600">
                    已选择：{selectedCells ? selectedCells.length : 0}/{task.spanLength}
                  </span>
                </p>
              </div>
            )}

            <Button
              onClick={handleAnswer}
              disabled={(task.type === 'digit_span' && !userInput.trim()) || 
                       (task.type !== 'digit_span' && (!selectedCells || selectedCells.length === 0))}
              className="w-full bg-gradient-to-r from-indigo-600 to-blue-500 hover:from-indigo-700 hover:to-blue-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              提交答案
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  // 格式化答案显示
  const formatAnswer = (answer: any[], taskType: string): string => {
    if (taskType === 'digit_span') {
      return answer.join('');
    } else if (taskType === 'spatial_sequence') {
      return answer.map((pos, i) => `${i + 1}:(${pos.x + 1},${pos.y + 1})`).join(' → ');
    } else if (taskType === 'visual_matrix') {
      return answer.map(pos => `(${pos.x + 1},${pos.y + 1})`).join(', ');
    }
    return '';
  };

  if (stage === 'feedback') {
    const task = tasks[currentTask];
    
    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.9 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto"
      >
        <Card className={`${feedbackCorrect ? 'border-green-200 bg-green-50' : 'border-red-200 bg-red-50'}`}>
          <CardContent className="p-6">
            {/* 顶部状态 */}
            <div className="text-center mb-6">
              <div className={`w-16 h-16 rounded-full mx-auto mb-4 flex items-center justify-center ${feedbackCorrect ? 'bg-green-100' : 'bg-red-100'}`}>
                {feedbackCorrect ? (
                  <CheckCircle className="w-8 h-8 text-green-600" />
                ) : (
                  <XCircle className="w-8 h-8 text-red-600" />
                )}
              </div>
              <h3 className={`text-xl font-semibold mb-2 ${feedbackCorrect ? 'text-green-800' : 'text-red-800'}`}>
                {feedbackCorrect ? '正确！' : '答错了'}
              </h3>
              {feedbackDetails && (
                <p className={`text-sm ${feedbackCorrect ? 'text-green-600' : 'text-red-600'}`}>
                  准确率：{feedbackDetails.accuracy}%
                </p>
              )}
            </div>

            {/* 答案对比 */}
            {feedbackDetails && !feedbackCorrect && (
              <div className="space-y-4">
                <div className="bg-white rounded-lg p-4 border">
                  <h4 className="font-semibold text-slate-800 mb-3">答案对比</h4>
                  
                  <div className="grid gap-3">
                    <div className="flex flex-col sm:flex-row gap-2">
                      <span className="font-medium text-green-700 min-w-[80px]">正确答案：</span>
                      <span className="font-mono text-green-800 bg-green-50 px-2 py-1 rounded">
                        {formatAnswer(feedbackDetails.correctAnswer, feedbackDetails.taskType)}
                      </span>
                    </div>
                    
                    <div className="flex flex-col sm:flex-row gap-2">
                      <span className="font-medium text-red-700 min-w-[80px]">您的答案：</span>
                      <span className="font-mono text-red-800 bg-red-50 px-2 py-1 rounded">
                        {feedbackDetails.userAnswer.length > 0 
                          ? formatAnswer(feedbackDetails.userAnswer, feedbackDetails.taskType)
                          : '未作答'
                        }
                      </span>
                    </div>
                  </div>
                </div>

                {/* 错误分析 */}
                {feedbackDetails.errors.length > 0 && (
                  <div className="bg-orange-50 border border-orange-200 rounded-lg p-4">
                    <h4 className="font-semibold text-orange-800 mb-3 flex items-center gap-2">
                      <XCircle className="w-4 h-4" />
                      错误分析
                    </h4>
                    <ul className="space-y-2">
                      {feedbackDetails.errors.map((error, index) => (
                        <li key={index} className="text-sm text-orange-700 flex items-start gap-2">
                          <span className="w-1.5 h-1.5 bg-orange-400 rounded-full mt-2 flex-shrink-0"></span>
                          <span>{error}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}

                {/* 提示信息 */}
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <h4 className="font-semibold text-blue-800 mb-2">💡 提示</h4>
                  <p className="text-sm text-blue-700">
                    {task.type === 'digit_span' && task.reverse 
                      ? '倒序记忆需要先记住数字，然后从最后一个开始倒着输入'
                      : task.type === 'digit_span' 
                      ? '数字序列记忆需要按照看到的顺序准确输入每一位数字'
                      : task.type === 'spatial_sequence'
                      ? '空间序列记忆需要按照方格高亮的时间顺序依次点击'
                      : task.type === 'visual_matrix'
                      ? '视觉矩阵记忆需要记住所有同时高亮的方格位置'
                      : '仔细观察并准确记忆是关键'
                    }
                  </p>
                </div>
              </div>
            )}

            {/* 正确反馈 */}
            {feedbackCorrect && (
              <div className="text-center">
                <p className="text-green-700 mb-4">
                  🎉 回忆准确，继续保持！
                </p>
                <div className="bg-green-100 border border-green-200 rounded-lg p-3">
                  <p className="text-sm text-green-700">
                    您的答案完全正确，工作记忆能力表现优秀！
                  </p>
                </div>
              </div>
            )}

            {/* 继续按钮 */}
            <div className="mt-6 text-center">
              <Button
                onClick={handleContinue}
                className="bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white px-8 py-2 shadow-lg hover:shadow-xl transition-all duration-200"
              >
                {currentTask < tasks.length - 1 ? '继续下一题' : '查看结果'}
              </Button>
            </div>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'results') {
    const totalTasks = tasks.length;
    const correctAnswers = score;
    const accuracy = Math.round((correctAnswers / totalTasks) * 100);
    const timeUsed = Math.round((Date.now() - startTime) / 1000);
    const averageSpan = responses.reduce((sum, r) => sum + r.spanLength, 0) / responses.length;

    // 按任务类型统计
    const typeStats: { [key: string]: { accuracy: number; count: number; avgSpan: number } } = {};
    
    responses.forEach(response => {
      const type = response.taskType;
      if (!typeStats[type]) {
        typeStats[type] = { accuracy: 0, count: 0, avgSpan: 0 };
      }
      typeStats[type].accuracy += response.accuracy;
      typeStats[type].avgSpan += response.spanLength;
      typeStats[type].count++;
    });

    // 计算平均值
    Object.keys(typeStats).forEach(type => {
      const stats = typeStats[type];
      stats.accuracy = Math.round((stats.accuracy / stats.count) * 100);
      stats.avgSpan = Math.round((stats.avgSpan / stats.count) * 10) / 10;
    });

    const getRating = () => {
      if (accuracy >= 90) return { text: '工作记忆专家', color: 'text-yellow-500' };
      if (accuracy >= 80) return { text: '优秀', color: 'text-green-500' };
      if (accuracy >= 70) return { text: '良好', color: 'text-blue-500' };
      if (accuracy >= 60) return { text: '一般', color: 'text-gray-500' };
      return { text: '需要提高', color: 'text-orange-500' };
    };

    const rating = getRating();

    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-lg">
          <CardHeader className="text-center">
            <div className="w-16 h-16 bg-gradient-to-br from-indigo-600 to-blue-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Brain className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">测试完成！</CardTitle>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="text-center space-y-4">
              <div className="text-6xl font-bold text-primary">
                {accuracy}
              </div>
              <div className={`text-xl font-semibold ${rating.color}`}>
                {rating.text}
              </div>
            </div>

            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center p-4 bg-green-50 dark:bg-green-950 rounded-lg">
                <div className="text-2xl font-bold text-green-600">{correctAnswers}</div>
                <div className="text-sm text-muted-foreground">正确任务</div>
              </div>
              <div className="text-center p-4 bg-blue-50 dark:bg-blue-950 rounded-lg">
                <div className="text-2xl font-bold text-blue-600">{totalTasks}</div>
                <div className="text-sm text-muted-foreground">总任务数</div>
              </div>
              <div className="text-center p-4 bg-purple-50 dark:bg-purple-950 rounded-lg">
                <div className="text-2xl font-bold text-purple-600">{averageSpan.toFixed(1)}</div>
                <div className="text-sm text-muted-foreground">平均广度</div>
              </div>
              <div className="text-center p-4 bg-orange-50 dark:bg-orange-950 rounded-lg">
                <div className="text-2xl font-bold text-orange-600">{timeUsed}s</div>
                <div className="text-sm text-muted-foreground">总用时</div>
              </div>
            </div>

            {/* 任务类型分析 */}
            <div className="space-y-3">
              <h3 className="text-lg font-semibold text-slate-800">分项表现</h3>
              {Object.entries(typeStats).map(([type, stats]) => (
                <div key={type} className="bg-slate-50 rounded-lg p-4">
                  <div className="flex justify-between items-center mb-2">
                    <span className="font-medium text-slate-700">
                      {type === 'digit_span' ? '数字广度' :
                       type === 'spatial_sequence' ? '空间序列' :
                       type === 'visual_matrix' ? '视觉矩阵' : type}
                    </span>
                    <Badge variant={stats.accuracy >= 80 ? 'default' : 'secondary'}>
                      {stats.accuracy}%
                    </Badge>
                  </div>
                  <div className="text-sm text-slate-600">
                    平均广度: {stats.avgSpan} | 完成任务: {stats.count}
                  </div>
                </div>
              ))}
            </div>

            <div className="flex gap-4">
              <Button 
                onClick={() => window.location.reload()}
                variant="outline" 
                className="flex-1 border-2 border-slate-300 hover:border-green-500 hover:bg-green-50 hover:text-green-700 transition-all duration-200"
              >
                <RotateCcw className="w-4 h-4 mr-2" />
                重新测试
              </Button>
              <Button 
                onClick={handleComplete}
                className="flex-1 bg-gradient-to-r from-green-500 to-emerald-500 text-white hover:from-green-600 hover:to-emerald-600 shadow-md hover:shadow-lg transition-all duration-200"
              >
                保存结果
              </Button>
            </div>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}